<template>
  <div>
    <a-modal
      v-drag-modal
      title="成果申报"
      class="resultAchievements"
      :visible="visible"
      :footer="null"
      :maskClosable="false"
      @cancel="handleCancel"
    >
      <a-form-model ref="ruleForm" :rules="rules" class="achievementsForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 15 }">
        <a-form-model-item label="成果名称：" prop="chengguo">
          <a-input v-model="form.chengguo" />
        </a-form-model-item>
        <a-form-model-item label="成果名称英文：">
          <a-input v-model="form.chengguoEnglish" />
        </a-form-model-item>
        <a-form-model-item label="关键词：" prop="keyword">
          <a-input v-model="form.keyword" />
        </a-form-model-item>
        <a-form-model-item v-if="flBh == 61" label="起始时间：" prop="startTime">
          <!-- <a-date-picker
            :inputReadOnly="true"
            :default-picker-value="moment(zlWcTime, dateFormat)"
            :disabled-date="disabledZlStartDate"
            @change="onStartChange"
            @openChange="handleStartOpenChange"
            format="YYYY-MM-DD"
            style="width: 100%"
            v-model="form.startTime"
          /> -->
          <a-date-picker
            :inputReadOnly="true"
            :default-picker-value="moment('2024-06-25', dateFormat)"
            :disabled-date="disabledZlStartDate"
            @change="onStartChange"
            @openChange="handleStartOpenChange"
            format="YYYY-MM-DD"
            style="width: 100%"
            v-model="form.startTime"
          />
        </a-form-model-item>
        <a-form-model-item v-else label="起始时间：" prop="startTime">
          <a-date-picker
            style="width: 100%"
            format="YYYY-MM-DD"
            :inputReadOnly="true"
            :default-picker-value="moment('2023-06-25', dateFormat)"
            :disabled-date="disabledStartDate"
            @change="onStartChange"
            @openChange="handleStartOpenChange"
            v-model="form.startTime"
          />
        </a-form-model-item>
        <a-form-model-item v-if="flBh == 61" label="截止时间：" prop="endTime">
          <a-date-picker
            :inputReadOnly="true"
            :default-picker-value="moment(zlWcTime, dateFormat)"
            :disabled-date="disabledZlEndDate"
            @change="onEndChange"
            name="finishTime"
            style="width: 100%"
            format="YYYY-MM-DD"
            v-model="form.endTime"
          />
        </a-form-model-item>
        <a-form-model-item v-else label="完成时间：" prop="endTime">
          <a-date-picker
            :inputReadOnly="true"
            :disabled-date="disabledEndDate"
            @change="onEndChange"
            @openChange="handleEndOpenChange"
            name="finishTime"
            style="width: 100%"
            format="YYYY-MM-DD"
            v-model="form.endTime"
          />
        </a-form-model-item>
        <a-form-model-item label="成果来源：" prop="laiyuan">
          <a-select @change="onCglylistChange" style="width: 100%;" v-model="form.laiyuan">
            <a-select-option v-for="(item, index) in cglylist" :value="item.cglyBh" :key="index">{{ item.cglyMc }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="具体计划名称和编号：">
          <a-input v-model="form.nameCode" />
        </a-form-model-item>
        <a-form-model-item label="成果申报类别：" prop="leibie">
          <a-input :disabled="true" v-model="form.leibie" />
        </a-form-model-item>
        <a-form-model-item v-if="flBh != '31'" label="申报类别小类：" prop="leibiexl">
          <a-cascader allowClear :options="options" placeholder="" v-model="form.leibiexl" />
        </a-form-model-item>
        <a-form-model-item v-if="flBh == '31'" label="申报类别小类：">
          <a-cascader disabled allowClear :options="options" placeholder="" v-model="form.leibiexl" />
        </a-form-model-item>
      </a-form-model>
      <div class="btns" style="">
        <a-button @click="handleSubmit" type="primary" html-type="submit" style="width:100px;height:40px;line-height:40px;">
          保存
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment';
import {
  cxjsbAdd,
  cxjsbCglylist,
  cxjsbValidlist,
  cxjsbLoadTreeRoot
} from '@/api/shenbao';
export default {
  props: {
    flag: null,
    flBh: null,
    flMc: null,
    zlTime: null
  },
  data() {
    this.dateFormat = 'YYYY-MM-DD';
    return {
      startValue: null,
      endValue: null,
      endOpen: false,
      visible: false,
      form: this.$form.createForm(this, { name: 'coordinated' }),
      source: '',
      cglylist: [],
      validlist: [],
      options: [],
      loadTreeRoot: [],
      startTime: '',
      endTime: '',
      xlFlag: true,
      form: {
        chengguo: "",
        chengguoEnglish: "",
        keyword: "",
        startTime: "",
        endTime: "",
        laiyuan: "",
        nameCode: "",
        leibie: "",
        leibiexl: []
      },
      rules: {
        chengguo: [{ required: true, message: '请输入成果名称', trigger: 'blur' }],
        keyword: [{ required: true, message: '请输入关键词', trigger: 'blur' }],
        startTime: [{ required: true, message: '请选择起始日期', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择完成日期', trigger: 'change' }],
        laiyuan: [{ required: true, message: '请选择成果来源', trigger: 'change' }],
        leibie: [{ required: true, message: '请选择成果申报类别', trigger: 'change' }],
        leibiexl: [{ required: true, message: '请选择申报类别小类', trigger: 'change' }]
      },
      zlWcTime: ""
    }
  },
  watch: {
    flag(next, prev) {
      if (next != prev) {
        var self = this;
        let year = self.zlTime - 1;
        self.zlWcTime = year + '' + '-12-31';
        self.visible = !self.visible;
        self.form.leibie = self.flMc;
        self.getCxjsbCglylist();
        self.getCxjsbValidlist();
        self.getCxjsbLoadTreeRoot(self.flBh);
      }
    }
  },
  methods: {
    moment,
    disabledStartDate(startValue) {
      // console.log('开始时间范围',startValue)
      // const endValue = this.form.endTime;
      // if (!startValue || !endValue) {
      //     return false;
      // }
      // return startValue.valueOf() > endValue.valueOf();

      const endValue = moment('2023-06-25');
      if (!startValue || !endValue) {
        return false;
      }
      return startValue.valueOf() > endValue.valueOf();
    },
    disabledEndDate(endValue) {
      const startValue = this.form.startTime;
      if (!endValue || !startValue) {
        return false;
      }
      return startValue.valueOf() >= endValue.valueOf();
    },
    disabledZlStartDate(startValue) {
      // const endValue = moment(this.zlTime-1+''+'-12-31');
      // const endValue = moment(this.zlWcTime);
      const endValue = moment('2024-06-25');
      if (!startValue || !endValue) {
        return false;
      }
      return startValue.valueOf() > endValue.valueOf();
    },
    disabledZlEndDate(endValue) {
      const startTime = moment(this.form.startTime);
      // 截止时间
      const endTime = moment(this.zlTime - 1 + '' + '-12-31');
      if (!endValue || !endTime) {
        return false;
      }
      return endValue.valueOf() < startTime.valueOf() || endValue.valueOf() > endTime.valueOf();
    },
    handleStartOpenChange(open) {
      // if (!open) {
      //     this.endOpen = true;
      // }
    },
    handleEndOpenChange(open) {
      // this.endOpen = open;
    },
    handleSubmit(e) {
      let that = this;
      e.preventDefault();
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let startTime = that.form.startTime.format('YYYY-MM-DD');
          let endTime = that.form.endTime.format('YYYY-MM-DD');
          console.log(startTime)
          console.log(endTime)
          let formData = new FormData();
          let reg = new RegExp(/\s/);
          if (reg.test(that.form.keyword)) {
            that.$message.warning('关键字中不能含有空格，多个关键字请使用逗号隔开！');
            return;
          }
          // 成果名称
          formData.append('cxj_mc_zw', that.form.chengguo)
          // 成果名称英文
          formData.append('cxj_mc_yw', that.form.chengguoEnglish ? that.form.chengguoEnglish : '')
          // 关键词
          formData.append('cxj_gjc', that.form.keyword)
          // 起始时间
          formData.append('cxj_qssj', startTime)
          // 完成时间
          formData.append('cxj_wcsj', endTime)
          // 成果来源
          formData.append('cxj_xmly', that.form.laiyuan)
          // 具体计划名称和编号
          formData.append('cxj_jhjjbh', that.form.nameCode ? that.form.nameCode : '')
          // 成果申报类别
          formData.append('fl_bh', that.flBh)
          // 申报类别小类
          if (that.flBh == '31') {
            formData.append('xl_bh', '');
          } else {
            formData.append('xl_bh', that.form.leibiexl.join(';'));
          }
          // 成果id
          formData.append('cxj_cxj_id', '');
          console.log('数据参数', that.form)
          that.$emit('declareAchievements', formData)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      /* that.form.validateFields((err, values) => {
          if (!err) {
              let formData = new FormData();
              let reg = new RegExp(/\s/);
              if (reg.test(values.keyword)) {
                  that.$message.warning('关键字中不能含有空格，多个关键字请使用逗号隔开！');
                  return;
              }
              // 成果名称
              formData.append('cxj_mc_zw', values.chengguo)
              // 成果名称英文
              formData.append('cxj_mc_yw', values.chengguoEnglish?values.chengguoEnglish:'')
              // 关键词
              formData.append('cxj_gjc', values.keyword)
              // 起始时间
              formData.append('cxj_qssj', that.startTime)
              // 完成时间
              formData.append('cxj_wcsj', that.endTime)
              // 成果来源
              formData.append('cxj_xmly', that.source)
              // 具体计划名称和编号
              formData.append('cxj_jhjjbh', values.nameCode?values.nameCode:'')
              // 成果申报类别
              formData.append('fl_bh', that.flBh)
              // 申报类别小类
              if (that.flBh == '31') {
                  formData.append('xl_bh', '');
              } else {
                  formData.append('xl_bh', values.leibiexl.join(';'));
              }
              // 成果id
              formData.append('cxj_cxj_id', '');
              that.$emit('declareAchievements', formData)
          }
      }) */
    },
    // 获取成果来源
    getCxjsbCglylist() {
      cxjsbCglylist().then(res => {
        let data = res.data;
        if (data.success) {
          this.cglylist = data.result;
        }
      })
    },
    // 获取成果分类列表
    getCxjsbValidlist() {
      cxjsbValidlist().then(res => {
        let data = res.data;
        if (data.success) {
          this.validlist = data.result;
          // console.log('成果分类列表',this.validlist)
        }
      })
    },
    // 重组成果小类
    convertAchievementsTree(tree) {
      var self = this;
      const result = [];
      // 遍历 tree
      tree.forEach(item => {
        // 读取 map 的键值映射
        const value = item.code;
        const label = item.title;
        let children = item.children;
        let children_arr = [];
        if (item.children && item.children.length) {
          children_arr = self.convertAchievementsTree(item.children);
        }
        // 如果有子节点，递归
        if (children && children.length > 0) {
          children = self.convertAchievementsTree(children);
          result.push({
            value,
            label,
            children
          });
        } else {
          var data = {
            value,
            label
          };
          result.push(data);
        }
      });
      return result;
    },
    // 获取成果小类
    getCxjsbLoadTreeRoot(id) {
      let data = {
        async: false,
        pcode: id
      }
      cxjsbLoadTreeRoot(data).then(res => {
        let data = res.data;
        if (data.success) {
          this.xlFlag = true;
          this.loadTreeRoot = data.result;
          this.options = this.convertAchievementsTree(data.result);
        } else {
          this.options = [];
          if (this.options.length) {
            this.xlFlag = true;
          } else {
            this.xlFlag = false;
          }
        }
      })
    },
    onCglylistChange(value) {
      console.log(value)
      // this.source = this.cglylist[value].cglyBh;
    },
    onStartChange(date, dateString) {
      this.startTime = dateString;
    },
    onEndChange(date, dateString) {
      this.endTime = dateString;
    },
    handleCancel(e) {
      this.visible = false;
      this.form = {
        chengguo: "",
        chengguoEnglish: "",
        keyword: "",
        startTime: "",
        endTime: "",
        laiyuan: "",
        nameCode: "",
        leibie: "",
        leibiexl: []
      };
    }
  }
}
</script>

<style lang="less">
.resultAchievements {
  .ant-modal-content {
    max-height: 750px !important;
  }
}

.achievementsForm {
  margin-bottom: 80px;
}

.btns {
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  bottom: 0;
  left: 0;
  background: #fff;

  .ant-form-item-control-wrapper {
    width: 100%;

    .ant-form-item-control {
      text-align: center;
    }
  }
}
</style>